package com.tianqu.tms.www.car.controller;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsController;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsDaoException;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.security.TmsUserProfile;
import com.tianqu.tms.core.util.DateUtil;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.core.webservice.weichat.api.MobileMessage;
import com.tianqu.tms.core.webservice.weichat.api.PullingExecutor;
import com.tianqu.tms.core.webservice.weichat.api.rpc.TransferDataSyn30500Bo;
import com.tianqu.tms.entity.Car;
import com.tianqu.tms.www.car.actionform.CarPendingLiftActionForm;


/**
 * @author huangheli 解挂确认
 */
public class CarLiftResultController extends TmsController {
	private Logger logger = Logger.getLogger(CarLiftResultController.class);
	public final static String PUSH_LICENSEPLATEYES_STR = "【库存挂起通知】您车行所登记的库存车辆（｛$车辆名称｝，｛$车牌号码｝）在｛$当前系统时间｝被系统自动进行库存挂起处理，此车辆之后将无法正常进出门禁系统。";
	public final static String PUSH_LICENSEPLATENO_STR = "【库存挂起通知】您车行所登记的库存车辆（｛$车辆名称｝，｛$VIN码｝）在｛$当前系统时间｝被系统自动进行库存挂起处理，此车辆之后将无法正常进出门禁系统。";
	public final static String PULL_LICENSEPLATEYES_STR = "【库存解挂通知】您车行所登记的库存车辆（｛$车辆名称｝，｛$车牌号码｝）在｛$当前系统时间｝被系统自动进行库存解挂处理，此车辆之后可以正常进出门禁系统。";
	public final static String PULL_LICENSEPLATENO_STR = "【库存解挂通知】您车行所登记的库存车辆（｛$车辆名称｝，｛$VIN码｝）在｛$当前系统时间｝被系统自动进行库存解挂处理，此车辆之后可以正常进出门禁系统。";
	public final static String CAR_NAME = "车辆名称";
	public final static String CAR_NUMBER = "车牌号码";
	public final static String CAR_VIN = "VIN码";
	public final static String SYSTEM_TIME = "当前系统时间";
	public final static String SIGN = "\\$";
	public final static String BEFOREBRACE = "｛";
	public final static String LATERBRACE = "｝";
	
	@Override
	public void execute(UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		TxController controller = TxController.getTxController();
		
		// 添加事务提交异常捕获
		try {
			controller.begin();
			CarPendingLiftActionForm form = (CarPendingLiftActionForm) uc.getInputForm();
			Car car = Car.getInstance();
			TmsUserProfile profile = uc.getUserProfile();
			
			//库存车辆信息表更新需要的数据
			car.setSerial(form.getSerial());
			car.setHandleType(form.getBarCodeNum());
			//解挂的同时要清除临时进出的时间,挂起的时候临时进出也是没有时间的，所以可以写为null
			//库存车辆信息表更新
			car.updateCarBarCodeNum(form.getSerial(),form.getBarCodeNum());
			
			//库存车辆特殊处理记录表需要的数据
			car.setIsPush(form.getIsPush());
			car.setUpdateUserId(profile.getUniqueId());
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式 			
			String updataTime = DateUtil.getCurrentTime();
			car.setUpdateTime(df.parse(updataTime));
			Car car1 = new Car();
			car1 = car1.findCarBySerial(form.getSerial());
			String pushContent = "";
			if(form.getIsPush() == 1)
			{
				if((form.getBarCodeNum() == 1) && !(car1.getLicensePlate() == null || car1.getLicensePlate().length() <= 0))
				{
					pushContent = getPushContent(car1.getCarName(),car1.getLicensePlate(),df.parse(updataTime),1);
				} else if((form.getBarCodeNum() == 1) && (car1.getLicensePlate() == null || car1.getLicensePlate().length() <= 0)){
					pushContent = getPushContent(car1.getCarName(),car1.getVin(),df.parse(updataTime),2);
				} else if((form.getBarCodeNum() == 2) && !(car1.getLicensePlate() == null || car1.getLicensePlate().length() <= 0)){
					pushContent = getPushContent(car1.getCarName(),car1.getLicensePlate(),df.parse(updataTime),3);
				} else if((form.getBarCodeNum() == 2) && (car1.getLicensePlate() == null || car1.getLicensePlate().length() <= 0)){
					pushContent = getPushContent(car1.getCarName(),car1.getVin(),df.parse(updataTime),4);
				}				
			}else if(form.getIsPush() == 2){			
				pushContent = "";
			}
			car.setPushContent(pushContent);
			car.setRemark(form.getRemark());
			
			//插入库存车辆特殊处理记录表
			car.insertCarHandleInfo(car);
			controller.commit();

			// 微信同步
			// CarManager api = CarManagerImpl.create();
			// api.lockOrUnLockCar(car.getSerial(),1);
			// MobileMessage message = new MobileMessage();
			// message.putValue("Serial", car.getSerial());
			// message.setMessage("解挂确认无法同步[挂起/解挂]接口,Serial为#Serial#");
			// LockOrUnLockCarBo api = new LockOrUnLockCarBo();
			// api.setMobileMessage(message);
			// api.setSerial(car.getSerial());
			// api.setRegisterStatus(1);
			// PullingExecutor.getInstance().submit(api);

			//
			// 5、【TMS】挂起/解挂 =》【车代办】同步
			
			MobileMessage message = new MobileMessage();
			message.putValue("Serial", form.getSerial());
			message.setMessage("【TMS】挂起/解挂 =》【车代办】同步,Serial为#Serial#");
			TransferDataSyn30500Bo api = new TransferDataSyn30500Bo();
			
			Car carInfo = Car.getInstance();
			carInfo = car.findMemberId(form.getSerial());
			api.setMobileMessage(message);
			api.setBarCodeNum(form.getBarCodeNum());
			api.setSerial(form.getSerial());
			if(carInfo != null)
			{
				api.setMemberId(String.valueOf(carInfo.getMemberId()));
				api.setStartTime(StringUtil.getTimeByTimeStamp(carInfo.getTmpStorageTime()));
				api.setEndTime(StringUtil.getTimeByTimeStamp(carInfo.getTmpEnterTime()));
			}
			api.setIsPush(car.getIsPush());
			api.setPushContent(car.getPushContent());
			api.setMarketNo(TmsConstants.MARKET_NO);
			PullingExecutor.getInstance().submit(api);
		} catch (Exception e) {
			try {
				controller.rollback();
			} catch (TransactionException e1) {
				throw new TmsException(TmsException.DB_TXCRROR, e1);
			}
			// 系统异常
			if (e instanceof TmsException) {
				throw e;
			}
			throw new TmsException(TmsException.DB_TXCRROR, e);
		}

		logger.debug(this.getClass().getName() + "#execute was completed.");
	}
	public String getPushContent(String carName,String carInfo,Date systemTime ,int type)
			throws TmsDaoException {
		String contentStr = "";
		//车牌号不为空的库存挂起信息
		if(type == 1)
		{
			carInfo = carInfo.substring(carInfo.length()-5, carInfo.length());
			contentStr = PUSH_LICENSEPLATEYES_STR;
		} else if(type == 2){
			carInfo = carInfo.substring(carInfo.length()-6, carInfo.length());
			//车牌号为空的库存挂起信息
			contentStr = PUSH_LICENSEPLATENO_STR;
		} else if(type == 3){
			carInfo = carInfo.substring(carInfo.length()-5, carInfo.length());
			//车牌号不为空的库存解挂信息
			contentStr = PULL_LICENSEPLATEYES_STR;
		} else if(type == 4){
			carInfo = carInfo.substring(carInfo.length()-6, carInfo.length());
			//车牌号为空的库存解挂信息
			contentStr = PULL_LICENSEPLATENO_STR;
		}
		contentStr = contentStr.replaceAll(SIGN, "").replaceAll(BEFOREBRACE, "").replaceAll(LATERBRACE, "");
		SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm");// 设置日期格式
		String sysTime = fm.format(systemTime);
		
		contentStr = contentStr.replaceAll(CAR_NAME, carName).replaceAll(CAR_NUMBER, carInfo)
		.replaceAll(CAR_VIN, carInfo).replaceAll(SYSTEM_TIME, sysTime); 
		
		return contentStr;
	}
}
